<template>
  <div class="form-preview-container">
    <div class="preview-header">
      <el-button type="primary" size="small" @click="goBack">
        <i class="el-icon-arrow-left"></i>
        返回
      </el-button>
      <span class="preview-title">表单预览</span>
      <el-button type="success" size="small" @click="submitForm">
        提交表单
      </el-button>
    </div>

    <div class="preview-content">
      <div v-if="loading" class="loading-container">
        <i class="el-icon-loading"></i>
        <p>正在加载表单...</p>
      </div>

      <div v-else-if="error" class="error-container">
        <i class="el-icon-warning"></i>
        <p>{{ error }}</p>
        <el-button type="primary" @click="goBack">返回设计器</el-button>
      </div>

      <div v-else class="form-container">
        <v-form-render
          ref="vFormRender"
          :form-json="formJson"
          :form-data="formData"
          :option-data="optionData"
        />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "FormPreview",
  data() {
    return {
      formJson: null,
      formData: {},
      optionData: {},
      loading: true,
      error: null,
    };
  },
  mounted() {
    this.loadFormFromUrl();
  },
  methods: {
    // 从localStorage加载表单JSON
    loadFormFromUrl() {
      try {
        // 检查URL参数中是否有templateId
        const urlParams = new URLSearchParams(window.location.search);
        const templateId = urlParams.get("templateId");

        if (templateId) {
          // 如果有templateId，从模板列表加载
          this.loadTemplateById(templateId);
        } else {
          // 否则从预览数据加载
          this.loadFromPreviewData();
        }
      } catch (error) {
        this.error = "加载表单失败：" + error.message;
        this.loading = false;
      }
    },

    // 根据模板ID加载模板
    loadTemplateById(templateId) {
      try {
        // 从localStorage获取模板列表
        const templatesJson = localStorage.getItem("vform-templates");
        if (!templatesJson) {
          this.error = "未找到模板数据";
          this.loading = false;
          return;
        }

        const templates = JSON.parse(templatesJson);
        const template = templates.find((t) => t.id === templateId);

        if (!template) {
          this.error = `未找到ID为${templateId}的模板`;
          this.loading = false;
          return;
        }

        this.formJson = template.formJson;

        if (!this.formJson || !this.formJson.widgetList) {
          this.error = "模板数据格式错误";
          this.loading = false;
          return;
        }

        this.loading = false;
      } catch (error) {
        this.error = "加载模板失败：" + error.message;
        this.loading = false;
      }
    },

    // 从预览数据加载
    loadFromPreviewData() {
      try {
        const previewJson = localStorage.getItem("vform-preview-json");
        const previewTimestamp = localStorage.getItem(
          "vform-preview-timestamp"
        );

        if (!previewJson) {
          this.error = "未找到表单数据，请先在设计器中设计表单";
          this.loading = false;
          return;
        }

        // 检查数据是否过期（超过1小时）
        if (
          previewTimestamp &&
          Date.now() - parseInt(previewTimestamp) > 3600000
        ) {
          localStorage.removeItem("vform-preview-json");
          localStorage.removeItem("vform-preview-timestamp");
          this.error = "预览数据已过期，请重新预览";
          this.loading = false;
          return;
        }

        this.formJson = JSON.parse(previewJson);

        if (!this.formJson || !this.formJson.widgetList) {
          this.error = "表单数据格式错误";
          this.loading = false;
          return;
        }

        this.loading = false;
      } catch (error) {
        this.error = "加载表单失败：" + error.message;
        this.loading = false;
      }
    },

    // 提交表单
    submitForm() {
      this.$refs.vFormRender
        .getFormData()
        .then((formData) => {
          console.log("表单数据:", formData);

          // 显示表单数据
          this.$alert(
            `<pre style="max-height: 400px; overflow: auto; text-align: left">${JSON.stringify(
              formData,
              null,
              2
            )}</pre>`,
            "表单提交成功",
            {
              dangerouslyUseHTMLString: true,
              confirmButtonText: "确定",
            }
          );
        })
        .catch((error) => {
          console.error("表单验证失败:", error);
          this.$message.error("表单验证失败，请检查必填项");
        });
    },

    // 返回上一页
    goBack() {
      // 检查URL参数中是否有templateId
      const urlParams = new URLSearchParams(window.location.search);
      const templateId = urlParams.get("templateId");

      if (templateId) {
        // 如果是从模板管理页面来的，返回模板管理页面
        this.$router.push("/templates");
      } else {
        // 否则返回设计器页面
        this.$router.push("/designer");
      }
    },
  },
};
</script>

<style scoped>
.form-preview-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.preview-header {
  background: #fff;
  padding: 15px 20px;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.preview-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.preview-content {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #909399;
}

.loading-container i {
  font-size: 32px;
  margin-bottom: 16px;
  animation: rotating 2s linear infinite;
}

.error-container i {
  font-size: 32px;
  margin-bottom: 16px;
  color: #f56c6c;
}

.loading-container p,
.error-container p {
  margin-bottom: 16px;
  font-size: 14px;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-container {
    margin: 0;
    padding: 20px;
    border-radius: 0;
  }

  .preview-header {
    padding: 10px 15px;
  }

  .preview-title {
    font-size: 16px;
  }
}
</style>
